<template>
  <div class="outter">
    <!-- 开头的添加搜索功能区 -->
    <div class="buttonsearch">
      <a-button type="primary" @click="addVisible = true"
        ><a-icon type="plus-circle" />新增管理人员</a-button
      >

      <div class="searchout">
        <a-button type="dashed" @click="reset">重置</a-button>
        <a-input-search
          style="width: 88%"
          placeholder="搜索管理人员"
          enter-button
          @search="onSearch"
        ></a-input-search>
      </div>
    </div>
    <div style="height: 450px; overflow: scroll">
      <a-table
        :columns="columns"
        :pagination="false"
        :data-source="data"
        bordered
        :tableLayout="`fixed`"
        :loading="tableLoading"
        :defaultExpandAllRows="true"
      >
        <!-- 修改名称部分 -->
        <template
          v-for="col in ['name', 'phone','email']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="(e) => handleTchange(e.target.value, record, col)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <!-- 操作方法部分 -->
        <template slot="method" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a-button :loading="record.saveloading" type="primary" @click="() => tsave(record)"
                >保存</a-button
              >
              <a-divider type="vertical" />
              <a-button @click="() => tcancel(record)">取消</a-button>
              <a-divider type="vertical" />
              <a-button
                @click="() => resetPassword(record)"
                type="dashed"
                :loading="resetPasswordLoading"
                >重置密码</a-button
              >
            </span>
            <span v-else>
              <a-button
                :disabled="editingKey !== ''"
                @click="() => tedit(record)"
                type="primary"
                
                >修改</a-button
              >
              <a-divider type="vertical" />
              <a-popconfirm
                :disabled="editingKey !== ''"
                title="确定删除吗？"
                @confirm="() => deletet(record)"
              >
                <a-button
                  :disabled="editingKey !== ''"
                  type="danger"
                  :loading="record.deleloading"
                >
                  删除
                </a-button>
              </a-popconfirm>
            </span>
          </div>
        </template>
        <template slot="role" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="!record.editable">
              {{ record.role }}
            </span>
            <span v-else-if="record.role==='经理'">
              {{ record.role }}
            </span>
            <span v-else>
              <a-select
                :default-value="record.role"
                style="width: 120px"
                @change="
                  (value) => {
                    selectChange(value, record);
                  }
                "
              >
                <a-select-option value="经理"> 经理 </a-select-option>
                <a-select-option value="服务员"> 服务员 </a-select-option>
                <a-select-option value="大厨"> 大厨 </a-select-option>
              </a-select>
            </span>
          </div>
        </template>
        <!-- 上传照片部分 -->
        <template slot="avatarUrl" slot-scope="text, record">
          <span v-if="!record.editable">
            <img
              :src="record.avatarUrl"
              alt=""
              style="height: 40px; width: 40px; border-radius: 10px"
            />
          </span>
          <span v-else>
            <a-upload
              name="file"
              :multiple="true"
              accept="image/*"
              :data="
                (file) => {
                  return { photo: file };
                }
              "
              :action="uploadUrl"
              @change="
                (info) => {
                  handleUrl(info, record);
                }
              "
              :show-upload-list="false"
            >
              <a v-if="!addloading" class="uploadimage" href="javascript:;">
                <img
                  :src="record.avatarUrl"
                  alt=""
                  style="height: 40px; width: 40px; border-radius: 10px"
                />
                <div class="zhezhao">修改</div>
              </a>
              <div v-else>
                <a-icon type="loading" />
              </div>
            </a-upload>
          </span>
        </template>
        <!-- 子代个数部分 -->
        <span slot="child" slot-scope="text, record">{{
          record.child.length
        }}</span>
        <!-- 嵌套的子表部分 -->
      </a-table>
    </div>
    <!-- 添加桌台弹出框 -->
    <a-modal
      title="添加管理人员"
      :visible="addVisible"
      :confirm-loading="confirmLoading"
      @ok="submitForm('RuleForm')"
      @cancel="handleCancel"
      okText="确认"
      cancelText="取消"
    >
      <a-form-model
        ref="RuleForm"
        :model="RuleForm"
        :rules="rule"
        v-bind="layout"
      >
        <a-form-model-item has-feedback label="姓名" prop="name">
          <a-input v-model="RuleForm.name" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="账号" prop="username">
          <a-input v-model="RuleForm.username" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="手机号" prop="phone">
          <a-input v-model="RuleForm.phone" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="邮箱账号" prop="email">
          <a-input v-model="RuleForm.email" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="权限" prop="role">
          <a-select
            default-value="经理"
            style="width: 120px"
            @change="
              (value) => {
                RuleForm.role = value;
              }
            "
          >
            <a-select-option value="经理"> 经理 </a-select-option>
            <a-select-option value="服务员"> 服务员 </a-select-option>
            <a-select-option value="大厨"> 大厨 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item has-feedback label="头像" prop="avatarUrl">
          <a-upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            accept="image/*"
            :data="
              (file) => {
                return { photo: file };
              }
            "
            :action="uploadUrl"
            @change="handleUrl"
          >
            <img
              v-if="RuleForm.avatarUrl"
              :src="RuleForm.avatarUrl"
              alt="avatar"
              style="width: 128px; height: 128px"
            />
            <div v-else>
              <a-icon :type="addloading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import VueConfig from "../../../vue.config.js";
import {
  userGet,
  userChange,
  searchUser,
  deleteUserinfo,
  addUser,
  resetUserPassword,
} from "@/api/user.js";
// 定义四列属性
const columns = [
  {
    title: "管理员姓名",
    dataIndex: "name",
    width: "10%",
    align: "center",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "管理员账号",
    dataIndex: "username",
    width: "8%",
    align: "center",
    scopedSlots: { customRender: "username" },
  },
  {
    title: "手机号",
    dataIndex: "phone",
    width: "9%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "phone" },
  },
  {
    title: "邮箱账号",
    dataIndex: "email",
    width: "14%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "email" },
  },
  {
    title: "头像",
    dataIndex: "avatarUrl",
    width: "10%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "avatarUrl" },
  },
  {
    title: "权限身份",
    dataIndex: "role",
    width: "13%",
    align: "center",
    ellipsis: true,
    scopedSlots: { customRender: "role" },
  },
  {
    title: "操作",
    dataIndex: "method",
    align: "center",
    scopedSlots: { customRender: "method" },
  },
];

export default {
  data() {
    // 添加菜单类别判断
    let validateNameValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    let validateCountValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else if (value.length > 13) {
        callback(new Error("账号不应该过长"));
      } else if (
        this.data.some((item) => {
          return item.username == value;
        })
      ) {
        callback(new Error("账号已存在"));
      } else {
        callback();
      }
    };
    let validatePasswordValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入初始密码"));
      } else {
        callback();
      }
    };
    let validatePhoneValue = (rule, value, callback) => {
      if (!/^\d+$/.test(value)) {
        callback(new Error("手机号必须为正纯数字"));
      } else {
        callback();
      }
    };
    let validateMailValue = (rule, value, callback) => {
      if (!/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
        callback(new Error("邮箱格式错误"));
      }else if (
        this.data.some((item) => {
          return item.email == value;
        })
      ) {
        callback(new Error("邮箱已存在"));
      } else {
        callback();
      }
    };
    //上传弹出框图片判断-共享
    let validateAvatarUrl = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    return {
      //form
      RuleForm: {
        name: "",
        username: "",
        password: "",
        phone: "",
        email:"",
        role: "经理",
        avatarUrl: "",
      },
      //form规则
      rule: {
        name: [
          { required: true, validator: validateNameValue, trigger: "change" },
        ],
        username: [
          { required: true, validator: validateCountValue, trigger: "change" },
        ],
        password: [
          {
            required: true,
            validator: validatePasswordValue,
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            validator: validatePhoneValue,
            trigger: "change",
          },
        ],
        email: [
          {
            required: true,
            validator: validateMailValue,
            trigger: "change",
          },
        ],
        avatarUrl: [
          { required: true, validator: validateAvatarUrl, trigger: "blur" },
        ],
      },
      //弹出框布局
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      //重置密码loading
      resetPasswordLoading: false,
      //上传弹出框图片loading-共享
      addloading: false,
      //添加菜类框是否可见
      addVisible: false,
      //表格Loading
      tableLoading: false,
      //确认提交表单loading-共享
      confirmLoading: false,
      //表格所需
      data: [],
      columns,
      //现在在修改的key
      editingKey: "",
      //用于取消修改时返回
      cachedata: [],
      //上传地址
      uploadUrl: "",
    };
  },
  mounted() {
    //创建缓存数据，缓存数据用来在修改取消时恢复
    this.aboutPerson(userGet);
    this.uploadUrl = "https://miswestrestaurant.xyz/test";
  },
  methods: {
    //搜索
    onSearch(res) {
      this.aboutPerson(searchUser, { name: res });
    },
    //搜索和第一次载入都用了相同的代码段
    aboutPerson(api, q) {
      this.tableLoading = true;
      let k = 0;
      api(q).then((res) => {
        res.data.map((item) => {
          item.key = k++;
          item.role = item.roles[0];
          item.deleloading = false
          item.saveloading=false
        });
        this.data = res.data;
        this.tableLoading = false;
        this.refreshCachedata();
      });
    },
    //刷新缓存数据
    refreshCachedata() {
      this.cachedata = JSON.parse(JSON.stringify(this.data));
    },
    //修改的四个关键方法
    handleTchange(value, record, column) {
      //newData只是一个临时存放点，关键在于刺激v-if进行判断
      const newData = [...this.data];
      record[column] = value;
      this.data = newData;
    },
    tedit(record) {
      //newData只是一个临时存放点，关键在于刺激v-if进行判断
      const newData = [...this.data];
      this.editingKey = record.key;
      console.log(this.editingKey);
      record.editable = true;
      this.data = newData;
    },
    tsave(record) {
      const newData = [...this.data];

      let tarr = Object.values(record);
      let message = "";
      for (let i = 0; i < tarr.length; i++) {
        console.log("看这个"+i)
        console.log([6,7,8,9,10,2].indexOf(i)!==-1)
        if (tarr[i] === ""&&[6,7,8,9,10,2].indexOf(i)===-1) {
          
          message = "不可有修改项为空！";
          break;
        }
        if (record.hasOwnProperty("phone") && !/^\d+$/.test(record.phone)) {
          message = "手机号必须为数字";
        }
        if (record.hasOwnProperty("email") && !/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(record.email)) {
          message = "邮箱格式错误";
        }
      }
      if (message != "") {
        this.$message.warn(message);
        return;
      }

      let query = {
        name: this.data[this.editingKey].name,
        roles: [this.data[this.editingKey].role],
        username: this.data[this.editingKey].username,
        phone: this.data[this.editingKey].phone,
        avatarUrl: this.data[this.editingKey].avatarUrl,
        email:this.data[this.editingKey].email
      };
      console.log(query);
      record.saveloading=true
      userChange(query).then(res=>{
        record.saveloading=false
         if(res.code===200){
           this.$message.success("修改成功");
          delete record.editable;
          this.data = newData;
          this.refreshCachedata();
          this.editingKey = "";
         }
      })
    },
    tcancel(record) {
      //不管是[...this.cachedata]还是object.assign整个付过去都会是浅拷贝，我这个效率最低但最省事
      this.editingKey = "";
      delete record.editable;
      this.data = JSON.parse(JSON.stringify(this.cachedata));
    },
    //处理每个修改或上传的照片
    handleUrl(info, record) {
      this.addloading = true;
      if (info.file.status === "done") {
        // record则为修改，this.RuleForm则为新增
        if (record) record.avatarUrl = info.file.response;
        else this.RuleForm.avatarUrl = info.file.response;
        this.$message.success(`${info.file.name} 上传成功`);
        this.addloading = false;
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
        this.addloading = false;
      }
    },

    //提交新增成员表单时
    submitForm(formName) {
      let thing;
      thing = {
        name: this.RuleForm.name,
        username: this.RuleForm.username,
        phone: this.RuleForm.phone,
        password: this.RuleForm.password,
        avatarUrl: this.RuleForm.avatarUrl,
        roles: [this.RuleForm.role],
        email: this.RuleForm.email
      }
      console.log(thing)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          addUser(thing).then((res) => {
            this.aboutPerson(userGet);
            if(res.code===200){
              this.$message.success("成功添加");
            }
            this.confirmLoading = false;
            this.addVisible = false;
            this.addFoodVisible = false;
            this.$refs[formName].resetFields();
          });
        } else {
          console.log("添加失败");
          return false;
        }
      })
    },

    //弹出框的取消
    handleCancel() {
      this.addVisible = false;
    },
    selectChange(value, record) {
      record.role = value;
    },

    //点击重置按钮时
    reset() {
      this.aboutPerson(userGet);
    },
    //点击删除按钮时
    deletet(record) {
      record.deleloading = true;
      deleteUserinfo({ username: record.username }).then((res) => {
        record.deleloading = false;
        if(res.code===200){
          this.$message.success("删除成功");
          this.aboutPerson(userGet);
        }
      });
    },
    //重置密码
    resetPassword(record) {
      this.resetPasswordLoading = true;
      resetUserPassword({ username: record.username }).then((res) => {
        this.resetPasswordLoading = false;
        if(res.code===200){
          this.$message.success("密码重置为123456");
        }
      });
    },
  },
};
</script>

<style scoped>
.outter {
  padding: 20px 10px;
}
.bottonheader {
  widows: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.buttons {
  width: 30%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.nima {
  width: 100%;
  height: 420px;
  background: rgb(217, 220, 223);
}

.editable-row-operations a {
  margin-right: 8px;
}
.buttonsearch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  margin-bottom: 25px;
}
.uploadimage {
  font-size: 1px;
  position: relative;
  display: block;
  /* transition: all 1s; */
}
.zhezhao {
  opacity: 0.6;
  background-color: rgb(95, 74, 74);
  transition: all 0.5s;
  color: aliceblue;
  top: 0;
  position: absolute;
  width: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 10px;
}

.searchout {
  width: 50%;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
